<?php

namespace App\Http\Service\Brand;

use App\Models\Categorymapping;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;


class CategorymappingService  extends BaseService
{
    private $model;

    public function __construct(Categorymapping $model)
    {
        parent::__construct();
        $this->model = $model;
       
    }

    public function getList($request,$data=[])
    {
        $page = intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit = intval($request->input('limit')) ?$request->input('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where = [
           ['standard_name','!=',''],
        ];
        $count = $this->model->where($where)->count();
        $fields = ['id','standard_name'];
        $list = $this->model->select($fields)
        ->where($where)
        ->offset($offset)->limit($limit)
        ->orderBy('id', 'desc')
        ->get()->toArray();
        $result = [
            'page'=> $page,
            'limit'=> $limit,
            'total_page'=> ceil($count/$limit),
            'count'=>$count,
            'data'=> $list
        ];
        return $result; 

    }
   
    /**
     *
     * @param array $params
     * @return array
     */
    public function addData($request,$data=[])
    {
        $original_name=$data['original_name'];
        $standard_name=$data['standard_name'];
        $list = [
            "其它品牌", 
            "其它",
            "其他家", 
            "其他品牌",
            "其他",
            "未知", 
            "", 
            "无",
            'others/其他'
           ];
        if (in_array($original_name,$list) || in_array($standard_name,$list)){
            $original_name= "未知品牌";
        }
        $first=$this->model->where(['original_name'=>$original_name])->first();
        if($first){
            $standard_name_arr=explode('/', $first['standard_name']);
            $standard_name_arr[]=$standard_name;
            $standard_name_arr=array_unique($standard_name_arr);
            $standard_name_str=implode('/', $standard_name_arr);
            $multiple_flag = 0;
            if (count($standard_name_arr) >1){
                $multiple_flag = 1;
            }
            $data1=[
                'standard_name'=>$standard_name_str,
                'multiple_flag'=>$multiple_flag
            ]; 
            $this->model->where(['original_name'=>$original_name])->update($data1);

        }else{
            $data2=[
                'original_name'=>$original_name,
                'standard_name'=>$standard_name,
                'multiple_flag'=>0,
                'error'=>0
            ];
            
            $res=$this->model->insertGetId($data2);
        }

        $this->success1();
        
    }

    //分类列表
    public function paramList($request,$data=[])
    {
        $level=$data['level'];
        $unique_name=$data['unique_name'];
        
       // dd($level);
        $where = [
           ['status','=','1'],
        ];
        if($unique_name){
             $where[]=['standard_name','like',$unique_name.'%'];
        }
        $fields = ['id','standard_name'];
        $list = $this->model->select($fields)
        ->where($where)
        ->orderBy('id', 'desc')
        ->get()->toArray();
        $result=[];
        foreach ($list as $k => $v) {
            $v_ar=explode('/',$v['standard_name']);
            switch ($level) {
                case '1':
                    $key=$v_ar[0];
                    $result[$key]=[
                        'id'=>$v['id'],
                        'name'=>$v_ar[0],
                        'unique_name'=>$v_ar[0],
                    ];
                    break;
                case '2':
                    if(isset($v_ar[1])){
                        $key=$v_ar[1];
                        $result[$key]=[
                            'id'=>$v['id'],
                            'name'=>$v_ar[1],
                            'unique_name'=>"{$v_ar[0]}/{$v_ar[1]}",
                        ];
                    }
                   
                    break;
                case '3':
                    if(isset($v_ar[2])){
                        $key=$v_ar[2];
                        $result[$key]=[
                            'id'=>$v['id'],
                            'name'=>$v_ar[2],
                            'unique_name'=>"{$v_ar[0]}/{$v_ar[1]}/{$v_ar[2]}",
                        ];
                    }
                    break;
                case '4':
                    if(isset($v_ar[3])){
                        $key=$v_ar[3];
                        $result[$key]=[
                            'id'=>$v['id'],
                            'name'=>$v_ar[3],
                            'unique_name'=>"{$v_ar[0]}/{$v_ar[1]}/{$v_ar[2]}/{$v_ar[3]}",
                        ];

                    }
                        
                    break;
                default:
                    // code...
                    break;
            }
            
        }
        $result=array_values($result);
        return $result;
    }

    #根据平台返回的分类获取目标分类
    public function targetCategory88888($original_name)
    {
        $first=$this->model->where(['original_name'=>$original_name])->first();
        $result="未知";
        if(empty($original_name)){
            return $result;
        }
        if(!$first){
           $data=[
                'original_name'=>$original_name,
                'standard_name'=>'未知',
           ];
           #判断是否要写入
           $first2=$this->model->where($data)->first();
           if(!$first2){
                $data['status']=1;
                $data['update_time']=date("Y-m-d H:i:s");
                $data['create_time']=date("Y-m-d H:i:s");
                $this->model->insertGetId($data);
           }
        }else{
            $result=$first['standard_name'];
        }
        return $result;
    }


    public function targetCategory($original_name)
    {
        if (empty($original_name)) {
            return "未知";
        }
        
        $cacheKey = 'category_mapping:' . md5($original_name);
        
        // 尝试从缓存获取
        $cachedResult = cache()->get($cacheKey);
        if ($cachedResult !== null) {
            return $cachedResult;
        }
        
        // 使用缓存锁防止缓存击穿
        $lockKey = 'category_lock:' . md5($original_name);
        $lock = cache()->lock($lockKey, 10);
        
        try {
            // 再次检查缓存（在获取锁期间可能已被其他进程填充）
            $cachedResult = cache()->get($cacheKey);
            if ($cachedResult !== null) {
                return $cachedResult;
            }
            
            if ($lock->get()) {
                // 查询数据库
                $existing = $this->model->where('original_name', $original_name)->first();
                
                if ($existing) {
                    $result = $existing->standard_name;
                } else {
                    // 插入新记录
                    $data = [
                        'original_name' => $original_name,
                        'standard_name' => '未知',
                        'status' => 1,
                        'update_time' => date("Y-m-d H:i:s"),
                        'create_time' => date("Y-m-d H:i:s")
                    ];
                    
                    try {
                        $this->model->insertGetId($data);
                        $result = '未知';
                    } catch (\Exception $e) {
                        // 处理重复插入
                        if (str_contains($e->getMessage(), 'Duplicate')) {
                            $existing = $this->model->where('original_name', $original_name)->first();
                            $result = $existing ? $existing->standard_name : '未知';
                        } else {
                            $result = '未知';
                        }
                    }
                }
                
                // 写入缓存
                cache()->put($cacheKey, $result, 3600);
                $lock->release();
                
                return $result;
            } else {
                // 获取锁失败，等待后重试或返回默认值
                usleep(100000); // 等待100ms
                return cache()->get($cacheKey, '未知');
            }
            
        } catch (\Exception $e) {
            if (isset($lock)) {
                $lock->release();
            }
            \Log::error('分类映射查询失败: ' . $e->getMessage());
            return '未知';
        }
    }



}
